package com.ray.business.strategy.order.cancel;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.ray.business.builder.BusinessBuilder;
import com.ray.business.builder.OrderDeleteIndexBuilder;
import com.ray.business.enums.BusinessStatusEnum;
import com.ray.business.service.*;
import com.ray.business.table.entity.ProdBusiness;
import com.ray.business.table.entity.ProdOrderDeleteIndex;
import com.ray.business.table.entity.ProdOrderGoods;
import com.ray.business.table.entity.ProdOrderStep;
import com.ray.magicBlock.Strategy;
import com.ray.magicBlock.anno.Block;
import com.ray.util.CodeSplitUtil;
import com.ray.wms.service.compose.InService;
import com.ray.woodencreate.beans.LoginUser;
import com.ray.woodencreate.exception.BusinessExceptionFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * @author bo shen
 * @Description: 订单商品数据
 * @Class: PurchaseInService
 * @Package com.ray.wms.strategy.in
 * @date 2020/6/8 15:05
 * @company <p>Ray快速开发平台</p>
 * @updateRecord time(修改时间)  author(修改人)   desc(修改内容)
 */
@Slf4j
@Block(group = "cancelBusiness", strategy = "in", desc = "取消业务")
public class InOrderCancelService implements Strategy<ProdBusiness, LoginUser, String> {

    @Autowired
    private ProdBusinessService prodBusinessService;
    @Autowired
    private ProdBusinessInService prodBusinessInService;
    @Autowired
    private ProdBusinessOutService prodBusinessOutService;
    @Autowired
    private InService inService;
    @Autowired
    private ProdOrderStepService prodOrderStepService;
    @Autowired
    private ProdOrderGoodsService prodOrderGoodsService;
    @Autowired
    private ProdOrderDeleteIndexService prodOrderDeleteIndexService;

    @Override
    public String execute(ProdBusiness prodBusiness, LoginUser loginUser) {

        BusinessBuilder businessBuilder = new BusinessBuilder();
        businessBuilder.appendCode(prodBusiness.getBusinessCode()).appendEdit(loginUser).appendStatus(BusinessStatusEnum.CANCEL.getValue());
        //更新
        prodBusinessService.edit(businessBuilder.bulid(), loginUser);
        List<ProdOrderDeleteIndex> deleteIndexList = new ArrayList<>();
        //还原对应出库的状态
        prodBusinessInService.listAll(prodBusiness.getBusinessCode(), loginUser).forEach(prodBusinessIn -> {
            //还原数据
            if (StrUtil.isNotBlank(prodBusinessIn.getOutCode())) {
                prodBusinessOutService.cancelBusinessOut(prodBusinessIn.getOutCode(), loginUser);
            }
            //组装列表
            if (ObjectUtil.isNotNull(prodBusinessIn.getIndexSort())) {
                deleteIndexList.add(new OrderDeleteIndexBuilder().appendOrderNo(prodBusiness.getOrderNo())
                        .appendGoodsCode(CodeSplitUtil.getFirst(prodBusiness.getGoodsCode()))
                        .appendCreate(loginUser).appendIndex(prodBusinessIn.getIndexSort()).bulid());
            }
        });
        //保存删除的序号
        if (ObjectUtil.isNotEmpty(deleteIndexList)) {
            prodOrderDeleteIndexService.saveBatch(deleteIndexList);
        }
        //删除原有的记录
        // prodBusinessInService.deleteByBusinessCode(businessCode, loginUser);
        //取消出入库单
        inService.invalidOrderBusinessCode(prodBusiness.getBusinessCode(), loginUser);
        //如果业务是从完成取消的 就需要处理退回完成数量
        //判断工序是否最后一步
        ProdOrderStep prodOrderStep = prodOrderStepService.queryStepByStepCode(CodeSplitUtil.getFirst(prodBusiness.getGoodsCode()),
                prodBusiness.getStepCode(), loginUser);
        if (ObjectUtil.isNotNull(prodOrderStep)) {
            //查询工序的下一步
            ProdOrderStep last = prodOrderStepService.queryStepByIndexSort(CodeSplitUtil.getFirst(prodBusiness.getGoodsCode()),
                    prodOrderStep.getIndexSort() + 1, loginUser);
            if (ObjectUtil.isNull(last)) {
                ProdOrderGoods orderGoods = prodOrderGoodsService.queryOrderGoodsByGoodsCode(prodBusiness.getOrderNo(),
                        prodBusiness.getGoodsCode(), loginUser);
                if (ObjectUtil.isNotNull(orderGoods)) {
                    BigDecimal finishQuantity = orderGoods.getFinishQuantity().subtract(prodBusiness.getQuantity());
                    Integer finishTotal = orderGoods.getTotal() - prodBusiness.getTotal();
                    if (!prodOrderGoodsService.updateFinishQuantity(prodBusiness.getOrderNo(), prodBusiness.getGoodsCode(),
                            finishQuantity, finishTotal, orderGoods.getUpdateVersion(), loginUser)) {
                        log.info("扣减订单完成数量异常");
                        throw BusinessExceptionFactory.newException("扣减订单完成数量异常");
                    }
                }
            }
        }
        return businessBuilder.getCode();
    }
}
